// Create the canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 800;
canvas.height = 600;
document.body.appendChild(canvas);

// paddle image
var paddleReady = false;
var paddleImage = new Image();
paddleImage.onload = function () {
	paddleReady = true;
};
paddleImage.src = "images/paddle.png";

// Ball image
var ballReady = false;
var ballImage = new Image();
ballImage.onload = function () {
	ballReady = true;
};
ballImage.src = "images/ball.png";

// Game objects
var paddle = {
	speed: 512 // movement in pixels per second
};
var ball = {
	speed: 256, // movement in pixels per second
	velx: 0.0,
	vely: 1.0 // start moving strait down
};

var Score = 0;

// Handle keyboard controls
var keysDown = {};

addEventListener("keydown", function (e) {
	keysDown[e.keyCode] = true;
}, false);

addEventListener("keyup", function (e) {
	delete keysDown[e.keyCode];
}, false);

// Reset the game when the player catches a ball
var reset = function () {
	paddle.x = canvas.width / 2 - 32;
	paddle.y = canvas.height - 50;

	// Place the ball 
	ball.x = canvas.width / 2 - 16;
	ball.y = canvas.height - 200;
};

// Update game objects
var update = function (modifier) {
	//todo add reset gamestate

	if (37 in keysDown) { // Player holding left
		paddle.x -= paddle.speed * modifier;
	}
	if (39 in keysDown) { // Player holding right
		paddle.x += paddle.speed * modifier;
	}
	
	ball.x += ball.speed * ball.velx * modifier;
	ball.y += ball.speed * ball.vely * modifier;

	// Are they touching?
	if (
		// ball is 32x32
		ball.vely > 0
		&& paddle.x <= (ball.x + 32)
		&& ball.x <= (paddle.x + 32)
		&& paddle.y <= (ball.y + 32)
		&& ball.y <= (paddle.y + 32)
	) {
		//Calculate the new angle of the ball
		ball.vely *= -1
		//todo calculate new x coefficient based on position of ball and paddle
		//reset();
	}
	// is the ball off the screen?
	if(ball.y <= 0) {
		//Calculate the new angle of the ball
		ball.vely *= -1
	}
	if( ball.y <= 0 || ball.y >= 600 - 32) {
		ball.velx *= -1;
	}
};

// Draw everything
var render = function () {
	//Draw the background
	ctx.fillStyle   = '#000'; // black

	// Draw some rectangles.
	ctx.fillRect  (0, 0, 800, 600);

	if (paddleReady) {
		ctx.drawImage(paddleImage, paddle.x, paddle.y);
	}

	if (ballReady) {
		ctx.drawImage(ballImage, ball.x, ball.y);
	}

	// Score
	ctx.fillStyle = "rgb(250, 250, 250)";
	ctx.font = "24px Helvetica";
	ctx.textAlign = "left";
	ctx.textBaseline = "top";
	ctx.fillText("Score: " + Score, 32, 32);
};

// The main game loop
var main = function () {
	var now = Date.now();
	var delta = now - then;

	update(delta / 1000);
	render();

	then = now;
};

// Let's play this game!
reset();
var then = Date.now();
setInterval(main, 1); // Execute as fast as possible
